#!/usr/bin/env node
/**
 * Created by udi on 17-7-14.
 */
'use strict';

var program = require('commander');

var fs = require("./util/async_file")
var jv = require("./util/jv")
var path = require('path');
var watch = require('node-watch');
var packjson = require("./package.json");

const {rmdir} = require('commandir')
//var fs = require("fs")


var cmd = program
    .version(packjson.version)
    .description(packjson.description)
    .usage('<-s 源文件夹> <-f 文件类型> <-c 配置>')
    .option('-s, --source <源文件夹>', "")
    .option('-t, --target [目标文件夹]', "\n" +
        "\t\t如果为空，则等于 source。 \n" +
        "\t\t如果 source 是以 lang结尾，则 target 用语言代码替换结尾的 lang。")
    .option('-f, --file-type <文件类型>', '如：-f js,css')
    .option('-c, --config <配置>', '使用伪Json格式，key表示tagName,value表示语言代码。如：-c c:cn,e:en')
    .option('-l, --language [当前语言]', '仅编译当前语言，配置项的key值。')
    .option('-t, --template [target结尾的语言替换符]', '默认值为lang，会把结尾的lang替换为相应的语言值。')
    .option('-e, --as-service [编译完后，后台继续运行]', '')
    .parse(process.argv);

if (!cmd.fileType || !cmd.source || !cmd.config) {
  cmd.outputHelp();
  return;
}

if (!cmd.template) {
  cmd.template = "lang";
}

if (!cmd.target) {
  cmd.target = cmd.source;
}

var config = {};
cmd.config.split(",").forEach(it => {
  var sect = it.split(':');
  config[sect[0]] = sect[1];
});


var allTagNames = Object.keys(config);


cmd.source = path.resolve(cmd.source);
cmd.target = path.resolve(cmd.target);


var fileTypes = cmd.fileType.split(",");

var targetHead = cmd.target;
if (targetHead.endsWith(cmd.template)) {
  targetHead = targetHead.slice(0, 0 - cmd.template.length);
}

function getTarget(path, language) {
  var ret = targetHead + "_" + language + path.slice(cmd.source.length)
  return ret;
}

(async function () {
  var handleFile = async function (path, isFile, noLogFile) {

    if (!noLogFile) {
      if (!isFile) {
        console.log("Folder:" + path);
      }
      else {
        console.log("       " + path);
      }
    }

    var content = null;
    var needTranslate = false;
    if (isFile) {
      content = await fs.readFileAsync(path, 'utf8');
      needTranslate = fileTypes.contains(it => path.endsWith("." + it));
    }

    for (var i = 0, len = allTagNames.length; i < len; i++) {
      var tag = allTagNames[i];
      if (cmd.language && (cmd.language != tag)) continue;

      var target = getTarget(path, config[tag]);
      if (isFile == false) {
        if (await jv.mkdirs(target) === false) {
          return false;
        }
        continue;
      }

      if (needTranslate == false) {
        jv.copyFile(path, target)
        continue;
      }

      fs.writeFileSync(target, jv.procTagLang(content, allTagNames, tag));
    }
  }

  if (cmd.asService) {
    watch(cmd.source, {recursive: true}, function (evt, name) {
      process.stdout.write(evt + ':' + name);

      var stat = fs.statSync(name);


      for (var i = 0, len = allTagNames.length; i < len; i++) {
        var tag = allTagNames[i];
        if (cmd.language && (cmd.language != tag)) continue;

        var target = getTarget(name, config[tag]);
        if (evt == "remove") {
          if (fs.existsSync(target) == false) continue;

          if (stat.isDirectory()) {
            rmdir(target);
          }
          else {
            fs.unlink(target);
          }
        }
        else {
          if (stat.isDirectory()) {
            if (fs.existsSync(target) == false) continue;
            jv.mkdirs(target)
          }
        }
      }

      if (evt == "update" && stat.isFile()) {
        handleFile(name, true, true);
      }

      console.log("\t\t(ok!)")
    });
  }

  console.log("______________________________________________")


  await jv.walkFile(cmd.source, handleFile);


  console.log("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯")
  console.log("完成!!");

})();




